//
//  MLWeiboData.swift
//  MLSina20160624
//
//  Created by manmanlang on 16/6/28.
//  Copyright © 2016年 manmanlang. All rights reserved.
//

import UIKit

class MLWeiboData: NSObject {
    ///微博时间
    var created_at: String?
    var createdStr:String? {
        return getTimeStr(created_at ?? "")
    }
    
    ///ID
    var id: Int64 = 0
    ///信息内容
    var text: String?
    ///来源
    var source: String? {
        didSet {
            sourceStr = getSourceString(source)
        }
    }
    
    var sourceStr: NSMutableAttributedString?
    
    ///用户信息
    var userInfo: MLUserInfo?
    ///转发微博
    var retweeted_status:MLWeiboData?
    ///转发数
    var reposts_count:Int = 0{
        didSet{
            repostsStr = getCountString(reposts_count, title: "转发")
        }
    }
    
    var comments_count:Int = 0{
        didSet{
            commentsStr = getCountString(comments_count, title: "评论")
        }
    }
    
    var attitudes_count:Int = 0{
        didSet{
            attitudesStr = getCountString(attitudes_count, title: "赞")
        }
    }
    ///配图数组
    var pic_urls:[MLPicture]?
    
    func getCountString(count: Int, title: String) -> String{
        if count <= 0 {
            return title
        }else if count > 0 && count < 1000{
            return "\(count)"
        }else {
            let countF = CGFloat(count / 100)/10
            var countStr = "\(countF)"
            //containsString 判断字符串是否包含字符串
            if countStr.containsString(".0"){
                countStr = countStr.stringByReplacingOccurrencesOfString(".0", withString: "")
            }
            
            return "\(countStr)k"
        }
        
    }
    func getSourceString(source: String?) ->NSMutableAttributedString{
        guard let s = source where s.containsString("\">") else{
            return getAttrbuteString("来自 那遥远的地方")
        }
        let startIndex = s.rangeOfString("\">")!
        let endIndex = s.rangeOfString("</")!
        
        let str = s.substringWithRange(startIndex.endIndex..<endIndex.startIndex)
        let name = "来自 \(str)"
        
        
        
        return getAttrbuteString(name)
    }
    
    func getAttrbuteString(name: String) -> NSMutableAttributedString{
        let attr = NSMutableAttributedString(string: name)
        let range = (name as NSString).rangeOfString("来自")
        
        attr.addAttribute(NSForegroundColorAttributeName, value: ThemeColor, range: range)
        return attr
    }
    //转发数
    var repostsStr: String?
    //评论数
    var commentsStr: String?
    //表态数
    var attitudesStr: String?
    
    override func setValue(value: AnyObject?, forKey key: String) {
        if key == "user" {
            guard let value = value as?[String: AnyObject] else {
                return
            }
            let user = MLUserInfo(dict: value)
            userInfo = user
        }else if key == "retweeted_status" {
            guard let v = value as?[String: AnyObject] else{
                return
            }
            let s = MLWeiboData(dict: v)
            retweeted_status = s
            
        }else if key == "pic_urls" {
            guard let v = value as?[[String:AnyObject]] else{
                return
            }
            var tempArray:[MLPicture] = [MLPicture]()
            for dic in v {
                let p = MLPicture(dict: dic)
                tempArray.append(p)
            }
            pic_urls = tempArray
            
        }else {
            //需要父类
            super.setValue(value, forKey: key)
        }
        
    }
    
    ///KVC构造函数
    init(dict:[String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
    }
    override var description: String{
        let keys = ["created_at", "id", "text", "source"]
        return dictionaryWithValuesForKeys(keys).description
    }
    
    
}

extension MLWeiboData {
    func getTimeStr(createAt: String) -> String{
        
        /*
         如果是今年
         - 如果是今天
         - 如果小于60秒  显示刚刚
         - 如果小于60分钟 显示XX分钟前
         - 如果小时24小时 显示XX小时前
         - 其他 显示 08月28日
         如果不是今年
         - 例如 2015-01-01 显示 2015年01月01日
         */
        
        
        
        let df = NSDateFormatter()
        df.dateFormat = "EEE MM dd HH:mm:ss z yyyy"
        df.locale = NSLocale(localeIdentifier: "en_US")
        let wbDate = df.dateFromString(createAt)!
        //let wbDate = wbDate1.dateByAddingTimeInterval(-3600 * 24)
        let isThisYear = wbIsThisYear(wbDate)
        if isThisYear {
            
            let calender = NSCalendar.currentCalendar()
            
            if calender.isDateInToday(wbDate) {
                let s = NSDate().timeIntervalSinceDate(wbDate)
                
                if s < 60 {
                    return "刚刚"
                }else if s >= 60 && s < 60 * 60 {
                    return "\(Int(s / 60))分钟前"
                }else{
                    return "\(Int(s / 3600))小时前"
                }
                
            } else if calender.isDateInYesterday(wbDate){
                
                df.dateFormat = "昨天 HH:mm"
                
                return df.stringFromDate(wbDate)
            }else{
                df.dateFormat = "MM月dd日 HH:mm"
                return df.stringFromDate(wbDate)
            }
            
        }else {
            
            df.dateFormat = "yyyy年MM月dd日 HH:mm"
            return df.stringFromDate(wbDate)
        }
    }
    func wbIsThisYear(wbDate: NSDate) -> Bool{
        let df = NSDateFormatter()
        df.locale = NSLocale(localeIdentifier: "en_US")
        df.dateFormat = "yyyy"
        let wbStr = df.stringFromDate(wbDate)
        let currentStr = df.stringFromDate(NSDate())
        
        if wbStr == currentStr {
            return true
        }else {
            return false
        }
        
    }
}
